#import "Amap.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import <Cordova/CDV.h>

@implementation Amap
@synthesize locationManager;
- (void)pluginInitialize{
    NSLog(@"begin");
    [AMapLocationServices sharedServices].apiKey = [[self.commandDelegate settings] objectForKey:@"api_key" ];
    self.locationManager = [[AMapLocationManager alloc] init];
}


- (void)getLocation:(CDVInvokedUrlCommand*)command
{
    [self.commandDelegate runInBackground:^{
        [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
        // 带逆地理（返回坐标和地址信息）
        [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
            CDVPluginResult* pluginResult = nil;

            if (error)
            {
                NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];

                if (error.code == AMapLocationErrorLocateFailed)
                {
                    return;
                }
            } else {
                NSString *latitude = [NSString stringWithFormat:@"%lf", location.coordinate.latitude];
                NSString *longitude = [NSString stringWithFormat:@"%lf", location.coordinate.longitude];

                NSMutableDictionary *retDic = [[NSMutableDictionary alloc]init];
                [retDic setObject:latitude forKey:@"latitude"];
                [retDic setObject:longitude forKey:@"longitude"];
                if (regeocode)
                {
                    [retDic setObject:regeocode.formattedAddress forKey:@"address"];
                    [retDic setObject:@"" forKey:@"country"];
                    [retDic setObject:regeocode.province forKey:@"province"];
                    if (regeocode.city) {
                        [retDic setObject:regeocode.city forKey:@"city"];
                    }
                    if (regeocode.district) {
                        [retDic setObject:regeocode.district forKey:@"district"];
                    }
                    if (regeocode.citycode) {
                        [retDic setObject:regeocode.citycode forKey:@"cityCode"];
                    }
                    if (regeocode.adcode) {
                        [retDic setObject:regeocode.adcode forKey:@"adCode"];
                    }
                }
                 pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:retDic];
            }
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        }];
    }];
   
}

@end